package com.db.httpserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.concurrent.*;
import java.util.logging.Logger;

public final class WorkerThread implements Runnable {

    private static Logger logger = Logger.getLogger(WorkerThread.class.getName());

    public static void startPool(int suggestedPort) throws IOException {
        Parameter.setPort(suggestedPort);
        Parameter.print();
        int port = Parameter.getPort();
        int workers = Parameter.getWorkers();
        int timeout = Parameter.getTimeout();
        timeout = 5;
        
        // create pool of worker threads
        ExecutorService executorService = Executors.newFixedThreadPool(workers);
        // create server socket
        ServerSocket serverSocket = new ServerSocket(port);
        // accept connections
        while (true) {
            Socket socket = serverSocket.accept();
            //socket.setSoTimeout(timeout);

            executorService.submit(new WorkerThread(socket), timeout);
        }
    }

    private final Socket socket;

    public WorkerThread(Socket socket) {
        this.socket = socket;
    }

    public void run() {
    	
    	// Worker.handleRequest(Socket)
        Worker worker = new Worker();
        try {
            worker.handleRequest(socket);
        } catch (SocketTimeoutException e) {
            Thread.currentThread().interrupt();
            logger.info("Stop worker by timeout");
        } catch (IOException e) {
            logger.warning(String.format("Error handle request. Message error: ", e.getMessage()));
        }

    }
}